from django.contrib.auth.backends import ModelBackend
from users.models import User
import re


class MyAuthenticateBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # 判斷username是否是手機號
            if re.match(r'1[3-9]\d{9}', username):
                user = User.objects.get(mobile=username)
            else:
                # 否則使用用戶名查詢
                user = User.objects.get(username=username)
                # 表錯誤
        except User.DoesNotExist:
            return None
        return user